import 'dart:io';

import 'event_bus.dart';

class LinkManSocket {
  LinkManSocket._();

  static final LinkManSocket instance = LinkManSocket._();
  WebSocket _webSocket;

  void connect(String url) {
    WebSocket.connect(url).timeout(Duration(seconds: 5)).then((value) {
      _webSocket = value;
      if (_webSocket != null) {
        _webSocket.listen(_onReceive,
            onDone: _onDone, onError: _onError, cancelOnError: true);
      }
    });
  }

  void send(String str) {
    if (_webSocket != null) {
      _webSocket.add("AAA");
    }
  }

  void _onReceive(data) {
    print("SOCKET------->_onError$data");
    EventBus().commit(EventKeys.EVENT_BUS_LINK_SOCKET, data);

  }

  void _onDone() {
    print("SOCKET------->_onDone");
  }

  void _onError(error) {
    print("SOCKET------->_onError$error");
  }

  void close() {
    if (_webSocket != null) _webSocket.close();
  }
}
